﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SportsStore.Models;

namespace SportsStore.Data.Implementation
{
    public class EfProductRepository : IProductRepository
    {
        public ApplicationDbContext Context { get; }

        public EfProductRepository(ApplicationDbContext ctx)
        {
            Context = ctx;
        }
        public IQueryable<Product> Products => Context.Products;

        public void SaveProduct(Product product)
        {
            if (product.Id == 0)
            {
                Context.Products.Add(product);
            }
            else
            {
                Product dbEntry = Context.Products.FirstOrDefault(p => p.Id == product.Id);
                if (dbEntry != null)
                {
                    dbEntry.Name = product.Name;
                    dbEntry.Description = product.Description;
                    dbEntry.Price = product.Price;
                    dbEntry.Category = product.Category;
                }
            }
            Context.SaveChanges();
        }

        public Product DeleteProduct(int productId)
        {
            var dbEntry = Context.Products.FirstOrDefault(p => p.Id == productId);
            if (dbEntry != null)
            {
                Context.Products.Remove(dbEntry);
            }
            return dbEntry;
        }
    }
}
